package com.smarthome.api.mobile.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.smarthome.common.mobile.Service;
import com.smarthome.core.ads.AdsService;
import com.smarthome.domain.bean.ShAds;
import com.smarthome.domain.common.Constants;
import com.smarthome.domain.mobile.MobileCodeEnum;
import com.smarthome.domain.mobile.MobileResponse;
import com.smarthome.domain.mobile.req.MobileCommonRequest;

/**
 * @author dhc 公用服务接口
 * @date 2015年11月3日 下午4:40:53
 * @title
 */
@org.springframework.stereotype.Service("mobile.common.service")
public class MobileComonService implements Service<MobileResponse<?>>{
	
	private  static final String bannerJSON = "/staticFiles/json/banner.json";
	private  static final String goodsJSON = "/staticFiles/json/goods.json";
	@Resource(name="adsService")
	private AdsService adsService;
	
	/**
	 * @title 获取banner 数据 多条数据 滚动
	 * @createTime 2015年11月3日 下午4:58:24
	 * @author dhc
	 */
	public void banners(MobileCommonRequest request,MobileResponse<Object> response ){
		String str = "";
	
		ShAds ads = new ShAds();
		ads.setStatus(1);
		ads.setLocation(1);
		
		ads.setResidenceId(request.getResidenceId());
		List<ShAds> adss = adsService.queryAds(ads);
		
		if(null == adss) adss = new ArrayList<ShAds>();
		if(adss.size() < 5){
			ads.setResidenceId( Constants.PLATFORM_MANAGE_RESIDENCE_ID);
			adss.addAll(adsService.queryAds(ads));
		}
		if(null == adss || adss.size() == 0){
			try {
				str = getFileStr(bannerJSON);
			} catch (IOException e) {
				e.printStackTrace();
			}
			response.setData(JSON.parse(str));
			return ;
		}
		
		List<Map> list =new ArrayList<Map>();
		for(ShAds a : adss){
			Map<String,Object> obj = new HashMap<String, Object>();
			if(!StringUtils.isBlank(a.getImages())){
				obj.put("img",a.getImages().split(",")[0]);
			}
			obj.put("images",a.getImages());
			obj.put("url", a.getUrl());
			obj.put("name",a.getTitle());
			obj.put("content",a.getContent());
			obj.put("id", a.getId());
			list.add(obj);
		}
		
		response.setData(list);
	}
	
	/**
	 * @title 获取首页展示商品
	 * @createTime 2015年11月3日 下午5:01:07
	 * @author dhc
	 */
	public void topGoods(MobileCommonRequest request,MobileResponse<Object> response){
		String str = "";
		try {
			str = getFileStr(goodsJSON);
		} catch (IOException e) {
			e.printStackTrace();
		}
		List list = (List) JSON.parse(str);
		List tip = new ArrayList();
		if(list.size() > 3){
			for(int i = 0;i< 3;i++){
				tip.add(list.get(i));
			}
		} else {
			tip = list;
		}
		response.setData(tip);
	}
	
	public void allGoods(MobileCommonRequest request,MobileResponse<Object> response){
		String str = "";
		try {
			str = getFileStr(goodsJSON);
		} catch (IOException e) {
			e.printStackTrace();
		}
		response.setData(JSON.parse(str));
	}
	
	
	public void bannerAd(MobileCommonRequest request,MobileResponse<Object> response){
		if(null == request.getBannerId()){
			response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_NOT_FULL);
			return ;
		}
		response.setData(getById(bannerJSON, request.getBannerId()));
		
	}
	
	
	public void getGoods(MobileCommonRequest request,MobileResponse<Object> response){
		if(null == request.getGoodId()){
			response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_NOT_FULL);
			return ;
		}
		response.setData(getById(bannerJSON, request.getGoodId()));
		
	}
	
	
	private Object getById(String fileName,Long id){
		Object obj = null;
		String str;
		try {
			str = getFileStr(fileName);
			List<Map> list = (List) JSON.parse(str);
			if(null == list) return null;
			for(Map map : list){
				if(map.get("id").toString().equals(id.toString())){
					return map;
				}
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return obj;
	}
	
	private  String  getFileStr(String fileStr) throws IOException{
		ClassLoader classLoader = Thread.currentThread()  
	            .getContextClassLoader();  
	    if (classLoader == null) {  
	        classLoader = ClassLoader.getSystemClassLoader();  
	    }  
	    java.net.URL url = classLoader.getResource("");  
	    String ROOT_CLASS_PATH = url.getPath() + "/";  
	    File rootFile = new File(ROOT_CLASS_PATH);  
	    String WEB_INFO_DIRECTORY_PATH = rootFile.getParent() + "/";  
	    File webInfoDir = new File(WEB_INFO_DIRECTORY_PATH);  
	    String SERVLET_CONTEXT_PATH = webInfoDir.getParent() + "/";  
	     //这里 SERVLET_CONTEXT_PATH 就是WebRoot的路径  
	    String path = SERVLET_CONTEXT_PATH + "/" + fileStr;  
	    path = path.replaceAll("%20", " ");  
	    File file = new File(path);
	    BufferedReader reader =new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
	    String timStr = "";
	    String tempString = null;
	    while ((tempString = reader.readLine()) != null) {
	    	timStr += tempString;
        }
	   // timStr = new String(timStr.getBytes("GBK"),"UTF-8");
	    
	    timStr = timStr.substring(timStr.indexOf('['));
	    return timStr.replaceAll(" ", "");
	}
}
